//
//  BKInputView.swift
//  BaoKeSwift
//
//  Created by geek-duan on 2017/10/17.
//  Copyright © 2017年 geek-duan. All rights reserved.
//

import UIKit

protocol BKInputViewDetagate: class {
    
    func sendText(text: String)
}

class BKInputView: UIView {
    
    weak var delegate: BKInputViewDetagate?

    /// - 键盘背景
    private lazy var inputViewBackgroundView: UIView = {
        let inputViewBackgroundView = UIView()
        inputViewBackgroundView.backgroundColor = UIColor.init(red: 0.80, green: 0.82, blue: 0.84, alpha: 1)
        return inputViewBackgroundView
    }()
    /// - 占位符
    private lazy var placeholder: UILabel = {
        let placeholder = UILabel()
        placeholder.text = "回复:"
        placeholder.font = UIFont.systemFont(ofSize: 16)
        placeholder.textColor = UIColor.lightGray
        return placeholder
    }()
    /// - 输入框
    private lazy var inputTextView: UITextView = {
        let inputTextView = UITextView.init()
        inputTextView.returnKeyType = .send
        inputTextView.font = UIFont.systemFont(ofSize: 16)
        inputTextView.backgroundColor = UIColor.init(red: 0.95, green: 0.95, blue: 0.95, alpha: 1)
        inputTextView.textColor = UIColor.black
        inputTextView.layer.cornerRadius = 4
        inputTextView.layer.masksToBounds = true
        inputTextView.layer.borderColor = UIColor.lightGray.cgColor
        inputTextView.layer.borderWidth = 0.5
        inputTextView.delegate = self
        return inputTextView
    }()
    
    init(To: String) {
        super.init(frame: CGRect())
        /// - 注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHidden(_:)), name: .UIKeyboardWillHide, object: nil)
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(hiddenInputView))
        tap.delegate = self
        self.addGestureRecognizer(tap)
        inputTextView.becomeFirstResponder()
        placeholder.text = "回复: " + To
        setUI()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
        NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: nil)
    }
    
    func show() {
        
        UIApplication.shared.keyWindow?.addSubview(self)
        self.snp.makeConstraints { (make) in
            make.left.top.bottom.right.equalToSuperview()
        }
    }
    
    @objc func hiddenInputView() {
        self.removeFromSuperview()
        inputTextView.resignFirstResponder()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// MARK: - SetUI
extension BKInputView {
   
    private func setUI() {
        /// - 设置本身属性
        backgroundColor = UIColor.black.withAlphaComponent(0.5)
        /// - 设置子控件UI
        addSubview(inputViewBackgroundView)
        inputViewBackgroundView.addSubview(inputTextView)
        inputTextView.addSubview(placeholder)
        
        inputViewBackgroundView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(50)
            make.height.equalTo(50)
        }
        inputTextView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.height.equalTo(35)
            make.centerY.equalToSuperview()
        }
        placeholder.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(5)
            make.top.equalToSuperview().offset(10)
            make.height.equalTo(15)
        }
    }
}

// MARK: - textViewdelegate\UIGestureRecognizerDelegate
extension BKInputView: UITextViewDelegate, UIGestureRecognizerDelegate {
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        
        if text == "\n" { //转义字符：表示enter
            if textView.text.count > 0 {
                delegate?.sendText(text: textView.text)
                textView.text = ""
                textViewDidChange(textView)
            }
            return false
        }
        if range.location + text.count > 150 { // 限制长度大小
            return false
        }
        return true
    }
    
    func textViewDidChange(_ textView: UITextView) {
        if textView.text.count == 0 {
            placeholder.isHidden = false
        } else {
            placeholder.isHidden = true
        }
        let maxHegiht: CGFloat = 111.5
        let frame = textView.frame
        let constraintSize = CGSize(width: frame.size.width, height: CGFloat.greatestFiniteMagnitude)
        var size = textView.sizeThatFits(constraintSize)
        if size.height >= maxHegiht {
            size.height = maxHegiht
            textView.isScrollEnabled = true
        } else {
            textView.isScrollEnabled = false
        }
        UIView.animate(withDuration: 0.3) {
            self.inputViewBackgroundView.snp.updateConstraints({ (make) in
                make.height.equalTo(size.height + 15)
            })
            textView.snp.updateConstraints({ (make) in
                make.height.equalTo(size.height)
            })
            self.layoutIfNeeded()
        }
    }
    
    // MARK: - UIGestureRecognizerDelegate
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        if touch.view == inputViewBackgroundView {
            return false
        }
        return true
    }
}

// MARK: - 键盘出现\隐藏
extension BKInputView {
    
    @objc private func keyboardWillShow(_ notification: Notification) {
        
        if  let info = notification.userInfo,
        let keyboardSize = info[UIKeyboardFrameEndUserInfoKey] as? CGRect {
            
            let height = keyboardSize.size.height
            UIView.animate(withDuration: 0.2, animations: {
                self.inputViewBackgroundView.snp.updateConstraints({ (make) in
                    make.bottom.equalTo(-height)
                })
                self.layoutIfNeeded()
            })
        }
    }
    
    @objc private func keyboardWillHidden(_ notification: Notification) {
        
        UIView.animate(withDuration: 0.2, animations: {
            self.inputViewBackgroundView.snp.updateConstraints({ (make) in
                make.bottom.equalToSuperview().offset(50)
            })
            self.layoutIfNeeded()
            self.hiddenInputView()
        })
    }
}
